package com.zx.service.Impl;/**
 * Author:JasonZ
 * Data:2023/4/18
 */

import com.zx.context.AccessContext;
import com.zx.dao.ECommerceBalanceDao;
import com.zx.entity.EcommerceBalance;
import com.zx.model.vo.LoginUserInfo;
import com.zx.service.IECommerceBalanceService;
import com.zx.vo.BalanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @program: ecommerce-parent
 * @description:
 * @author: JasonZ
 * @create: 2023-04-18 13:59
 **/
@Service
@Slf4j
public class ECommerceBalanceServiceImpl implements IECommerceBalanceService {
    @Resource
    private ECommerceBalanceDao eCommerceBalanceDao;

    /*获取当前用户信息*/
    @Override
    public BalanceInfo getCurrentUserBalance() {
        //1.获取当前用户
        LoginUserInfo currentUser = AccessContext.getUserInfo();
        //2.判断当前用户是否开通了账户 未开通则开通账户
        //创建一个空的账户对象
        BalanceInfo balanceInfo = new BalanceInfo(
                currentUser.getId(),
                0l
        );
        //查询当前用户的账户余额信息
        EcommerceBalance ecommerceBalance = eCommerceBalanceDao.getEcommerceBalanceByUserId(currentUser.getId());
        //
        if (ecommerceBalance == null) {
            //创建新的账户 余额为0
            EcommerceBalance newBalance = new EcommerceBalance();
            newBalance.setUserId(currentUser.getId());
            newBalance.setBalance(0l);
            eCommerceBalanceDao.save(newBalance);
        } else {
            //账户不为空 给空的账户对象进行赋值
            balanceInfo.setBalance(ecommerceBalance.getBalance());
        }
        return balanceInfo;
    }

    /*当前用户购买商品之后的余额*/
    @Override
    public BalanceInfo deductBalance(BalanceInfo balanceInfo) {
        //获取当前用户信息
        LoginUserInfo currentUser = AccessContext.getUserInfo();
        //查询当前用户的账户信息
        /*BalanceInfo currentUserBalance = this.getCurrentUserBalance();*/
        EcommerceBalance currentBalance = eCommerceBalanceDao.getEcommerceBalanceByUserId(currentUser.getId());
        //做判断
        if (currentBalance == null) {
            throw new RuntimeException("请开通账户");
        }
        if (currentBalance.getBalance() - balanceInfo.getBalance() < 0) {
            throw new RuntimeException("用户余额不足");
        }
        currentBalance.setBalance(currentBalance.getBalance() - balanceInfo.getBalance());
        EcommerceBalance ecommerceBalance = eCommerceBalanceDao.save(currentBalance);
        return new BalanceInfo(
                currentBalance.getId(),
                ecommerceBalance.getBalance()
        );
    }
}
